import { watch, computed, ref, unref } from 'vue';

export const useForm = (props, emits) => {
  let formModel = ref({});
  let formRefLocal = ref(null);

  const saveRef = e => {
    formRefLocal.value = e.value;
  };

  /**
   * @description: 搜索事件/查询
   * @returns: search 方法 返回当前的输入值
   */
  const onSearch = () => {
    emits('search', formModel);
  };

  /**
   * @description: 重置表单
   * @param: formRef<ref> 子组件返回的ref模版 可以调用子组件中的方法
   * @returns: reset 重置表单，将formModel清空
   */
  const onReset = () => {
    formRefLocal.value.resetFields();
    emits('reset', formModel);
  };

  const changeValue = e => {
    emits('change', e);
  };
  /**
   * @description:  setFilesValue
   * @param:
   * @returns:
   */
  const setSearchValue = obj => {
    if (!obj) formModel.value = {};
    for (let key in obj) {
      formModel.value[key] = obj[key];
    }
  };
  /**
   * @description: getFilesValue
   * @param:
   * @returns:
   */
  const getSearchValue = () => {
    return formModel.value;
  };

  /**
   * @description: 监听model的变化并且赋值
   * @param: props.model 父组件传入的model
   * @returns: 重新赋值，避免子组件修改父组件
   */
  watch(
    () => props.model,
    model => {
      if (!model) return;
      setSearchValue(model);
    },
    { immediate: true, deep: true }
  );

  function initDefault() {
    const configs = unref(props.configs);
    configs.forEach(item => {
      const { defaultValue } = item;
      if (defaultValue !== null || defaultValue !== undefined) {
        if (formModel.value[item.key] === undefined) {
          formModel.value[item.key] = defaultValue;
        }
      }
    });
  }

  /**
   * @description 监听cofnigs的变化，根据defaultValue 设置表单的默认值
   */
  watch(
    () => props.configs,
    configs => {
      if (configs.length) {
        initDefault();
      }
    },
    { immediate: true, deep: true }
  );
  return {
    saveRef,
    formModel,
    onSearch,
    onReset,
    changeValue,
    setSearchValue,
    getSearchValue,
  };
};
